package com.lwlk.zdk.controller.Vehicle;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwlk.zdk.annotation.JwtIgnore;
import com.lwlk.zdk.annotation.MyLog;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.T.*;
import com.lwlk.zdk.mapper.pw.*;
import com.lwlk.zdk.mapper.sys.sysEnterpriseMapper;
import com.lwlk.zdk.mapper.wd.wdHfAreaMapper;
import com.lwlk.zdk.mapper.wd.wdIndustryDictionaryMapper;
import com.lwlk.zdk.model.CommonUser;
import com.lwlk.zdk.model.Encapsulation.EncapsulationCluster;
import com.lwlk.zdk.model.Encapsulation.EncapsulationVehicle;
import com.lwlk.zdk.model.T.TRegion;
import com.lwlk.zdk.model.pw.pwImagePath;
import com.lwlk.zdk.model.pw.pwVehicle;
import com.lwlk.zdk.model.pw.pwVehicleHistoryEnterprise;
import com.lwlk.zdk.model.pw.pwVehiclePath;
import com.lwlk.zdk.model.T.TDisStaff;
import com.lwlk.zdk.model.T.TDisVehicle;
import com.lwlk.zdk.service.CarService.CarService;
import com.lwlk.zdk.service.User.SysUserService;
import com.lwlk.zdk.util.*;
import com.lwlk.zdk.util.Base64s;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import javafx.util.converter.LongStringConverter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.time.DateUtils;
import org.w3.x2000.x09.xmldsig.ObjectType;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value = "车辆信息")
@RestController
@RequestMapping(value = "/vehicle")
public class VehicleController {



    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    private static String imagePath = PropUtils.getString("image.path");

    private static String imageServerBaseUrl = PropUtils.getString("image.server.baseUrl");

    private static final Logger log = LoggerFactory.getLogger(VehicleController.class);

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private static Date date=new Date();

    @Autowired
    pwVehiclePathMapper pwVehiclePathMapper;
    @Autowired
    TDisVehicleMapper tDisVehicleMapper;
    @Autowired
    TDisDictionaryMapper tDisDictionaryMapper;
    @Autowired
    TDisPlatformMapper tDisPlatformMapper;
    @Autowired
    TDisEnterpriseMapper tDisEnterpriseMapper;
    @Autowired
    TDisVehicleMapper disVehicleMapper;
    @Autowired
    TDisDictionaryMapper disDictionaryMapper;
    @Autowired
    TRegionMapper tRegionMapper;
    @Autowired
    TDisStaffMapper disStaffMapper;
    @Autowired
    TDisStaffMapper tDisStaffMapper;
    @Autowired
    pwVehicleHistoryEnterpriseMapper vehicleHistoryEnterpriseMapper;
    @Autowired
    pwImagePathMapper imagePathMapper;
    @Autowired
    pwUserMapper pwUserMapper;

    @ApiOperation(value = "车辆添加接口")
    @MyLog(value = "添加车辆信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Response add(@RequestBody TDisVehicle disVehicle,HttpServletRequest request) {
        Response response =new Response();
        try {//缺少车辆经营范围
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            List<TDisVehicle> disVehicles = disVehicleMapper.findUserByUsername(disVehicle.getVehicleNumber());
            if (disVehicles.size()>0){
                response.setCode(RetCode.ACCOUNT_NULL);
                response.setMsg("此车牌已存在,请重新添加");
                return response;
            }
            Integer vehicleId=tDisVehicleMapper.selectMaxVehicleId()+1;
            disVehicle.setVehicleId(vehicleId);
            disVehicle.setNetStatus(0);
            disVehicle.setDelFlag((short) 1);
            disVehicle.setCreateDate(new Date());
            int count = tDisVehicleMapper.insertSelective(disVehicle);
            response.setCode(RetCode.SUCCESS);
            response.setData(count);
            response.setMsg("操作成功");
            return response;
        }catch (Exception e){
            e.printStackTrace();
            response.setCode(RetCode.IDENTICAL);
        }
     return response;
    }


    @ApiOperation(value = "发证机构展示")
    @RequestMapping(value = "/certificateOrganization",method = RequestMethod.GET)
    public Response getCertificateOrganization(Integer id){
        Response response=new Response();
        List<Map<String, Object>> regionList = tRegionMapper.selectCertificateOrganization(id);
        response.setData(regionList);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "根据账号等级和所属地区查询所属企业")
    @RequestMapping(value = "/showEnterpriseId",method = RequestMethod.GET)
    public Response getShowEnterpriesName(Integer regionCode,Integer level,String enterpriseName){
        Response response=new Response();
        Integer areaCode=null;
        if (level==1){
            areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,2));
        }else if (level==2){
            areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,4));
        }else if (level==3){
            areaCode= regionCode;
        }
        List<Map<String,Object>>enterpriseNameList=tDisEnterpriseMapper.selectEnterpriseIdAndName(areaCode,enterpriseName);
        response.setData(enterpriseNameList);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;

    }

    @ApiOperation(value = "绑定平台(接入车辆页面)")
    @RequestMapping(value = "/bindingPlatformAndVehicle",method = RequestMethod.GET)
    public Response getBindingPlatformAndVehicle(Integer platformId,Integer vehicleId){
        Response response=new Response();
        int i=disVehicleMapper.updateBindingPlatform(platformId,vehicleId);
        response.setData(i);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }


    @ApiOperation(value = "车辆批量添加接口")
    @MyLog(value = "批量添加车辆信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/batch",method = RequestMethod.POST)
    public Response batch(@RequestBody EncapsulationVehicle vehicle){
        Response response=new Response();
        for (TDisVehicle tDisVehicle : vehicle.gettDisVehicleList()) {
            int count = tDisVehicleMapper.insertSelective(tDisVehicle);
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }


    @ApiOperation(value = "车辆修改接口")
    @MyLog(value = "修改车辆信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Response update(@RequestBody TDisVehicle disVehicle,HttpServletRequest request){
        Response response =new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            Boolean flage=listerUtil.getVehicle(request,disVehicle);
            if (flage==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("不可修改账号所属地区以外的信息");
                return response;
            }
            int count=tDisVehicleMapper.updateByPrimaryKeySelective(disVehicle);
            response.setCode(RetCode.SUCCESS);
            response.setData(count);
            response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    @ApiOperation(value = "添加车辆牌照不可相同")
    @RequestMapping(value = "/is_exist_vehicleNumber",method = RequestMethod.GET)
    public Response getVehicleNumber(String vehicleNumber){
        Response response=new Response();
        int i=tDisVehicleMapper.selectManyVehicleNumber(vehicleNumber);
        if (i>0){
            response.setCode(RetCode.VEHICLENUMBER_EXIST);
        }else {
            response.setCode(RetCode.USABLE_SUCCESS);
        }
        return response;
    }


    @ApiOperation(value = "车辆批量删除")
    @MyLog(value = "批量删除车辆信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/deleteBatch",method = RequestMethod.POST)
    public Response deleteBatch(Integer[] ids){
        Response response=new Response();
        int count=tDisVehicleMapper.deleteBatch(ids);
        response.setData(count);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }


    @ApiOperation(value = "车辆删除接口")
    @MyLog(value = "删除车辆信息")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Response delete(Integer id,HttpServletRequest request){
           Response response=new Response();
           try {
               TDisVehicle disVehicle=disVehicleMapper.selectByPrimaryKey(id);
               Boolean flag=listerUtil.getRoleType(request);
               if (flag==false){
                   response.setCode(RetCode.ACCOUNT_EXIST);
                   response.setMsg("此账号为监管员账号,不可进行操作");
                   return response;
               }
               Boolean flage=listerUtil.getVehicle(request,disVehicle);
               if (flage==false){
                   response.setCode(RetCode.ACCOUNT_EXIST);
                   response.setMsg("不可删除账号所属地区以外的信息");
                   return response;
               }
               int count=tDisVehicleMapper.deleteByPrimaryKey(id);
               response.setData(count);
               response.setCode(RetCode.SUCCESS);
               response.setMsg("执行成功");

           }catch (Exception e){
               e.printStackTrace();
           }
           return response;
        }

    @ApiOperation(value = "车辆删除接口(逻辑删除)")
    @MyLog(value = "车辆删除接口(逻辑删除)")
    @RequestMapping(value = "/logicallyDelete",method = RequestMethod.POST)
    public Response getLogicallyDelete(Integer vehicleId,HttpServletRequest request){
        Response response=new Response();
        TDisVehicle disVehicle=disVehicleMapper.selectByPrimaryKey(vehicleId);
        Boolean flag=listerUtil.getRoleType(request);
        if (flag==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("此账号为监管员账号,不可进行操作");
            return response;
        }
        Boolean flage=listerUtil.getVehicle(request,disVehicle);
        if (flage==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("不可删除账号所属地区以外的信息");
            return response;
        }
        int count=tDisVehicleMapper.deleteByPrimaryKey(vehicleId);
        response.setData(count);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "车辆批量删除接口(逻辑删除)")
    @MyLog(value = "车辆批量删除接口(逻辑删除)")
    @RequestMapping(value = "/logicallyDeleteBatch",method = RequestMethod.POST)
    public Response getLogicallyDeleteBatch(Integer[] ids){
        Response response=new Response();
        Integer i=null;
        for (Integer id : ids) {
            i=tDisVehicleMapper.updateDelFlag(id);
        }
        response.setData(i);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "车辆更换绑定企业的信息")
    @RequestMapping(value = "/vehicleBindingMessage",method = RequestMethod.POST)
    public Response getMessage(@RequestBody pwVehicleHistoryEnterprise pwVehicleHistoryEnterprise){
      Response response=new Response();
        int i=vehicleHistoryEnterpriseMapper.insertSelective(pwVehicleHistoryEnterprise);
        response.setData(i);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "分页展示车辆历史分析")
    @RequestMapping(value = "/showVehicleBindingMessage",method = RequestMethod.GET)
    public LayuiTablePagingResult getShowVehicleBinding(Integer page, Integer size,pwVehicleHistoryEnterprise pwVehicleHistoryEnterprise,Integer level){
         LayuiTablePagingResult result=null;
         try {
             Integer regionCode=null;
             if (level==1){
                 regionCode= Integer.valueOf(String.valueOf(pwVehicleHistoryEnterprise.getRegionCode()).substring(0,2));
             }else if (level==2){
                 regionCode= Integer.valueOf(String.valueOf(pwVehicleHistoryEnterprise.getRegionCode()).substring(0,4));
             }else if (level==3){
                 regionCode= Integer.valueOf(pwVehicleHistoryEnterprise.getRegionCode());
             }
             PageHelper.startPage(page,size);
             List<Map<String,Object>> vehicleHistoryList=vehicleHistoryEnterpriseMapper.selectDim(pwVehicleHistoryEnterprise);
             PageInfo pageInfo = new PageInfo(vehicleHistoryList);
             result = new LayuiTablePagingResult();
             result.setCode(RetCode.SUCCESS.getCode());
             result.setMsg(RetCode.SUCCESS.getMsg());
             result.setCount(pageInfo.getTotal());
             result.setData(pageInfo.getList());
             Long totalPages = pageInfo.getTotal() / size;
             if (pageInfo.getTotal() % size != 0){
                 totalPages ++;
             }
             result.setTotalPages(totalPages);

         }catch (Exception e){
             e.printStackTrace();
         }
        return result;
    }



    @ApiOperation(value = "查询车辆入网状态接口")
    @RequestMapping(value = "/netstatus",method = RequestMethod.GET)
    public JSONObject getNetstatus(String vids){

            String url = "http://"+Ip+":"+port+"/dis/v1/vehicle/realtime/netstatus";
            Map map=new HashMap();
            map.put("vids",vids);//必选 车辆id，多个id以英文逗号分隔
           Set<String> set = map.keySet();
           Iterator<String> it = set.iterator();
           while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
           Map<String,String>headMap=new HashMap<>();
           headMap.put("clientCode",clientCode);
           String result = HttpClientUtils.doGet(url,headMap,map);
           JSONObject json= JSONObject.parseObject(result);
           JSONArray jsonArray=json.getJSONArray("result");
           if (jsonArray==null){
              return json;
          }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            String vehicleNumber=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("vehicleNumber",vehicleNumber);
        }
            return json;

    }


    @ApiOperation(value = "车辆展示接口")
    @RequestMapping(value = "/show",method = RequestMethod.GET)
    public LayuiTablePagingResult show(Integer platformId, String vehicleNumber, Integer vehicleType, String enterpriseName, Integer networkState, Short vehicleLicenseColor, Integer page, Integer size,Integer areaCode,Integer level){
      LayuiTablePagingResult result=null;
      try {
          PageHelper.startPage(page,size);
          String onlineStatus="";
/*          Integer regionCode=null;
          if (level==1){
              regionCode= Integer.valueOf(String.valueOf(areaCode).substring(0,2));
          }else if (level==2){
              regionCode= Integer.valueOf(String.valueOf(areaCode).substring(0,4));
          }else if (level==3){
              regionCode= areaCode;
          }
          if (vehicleNumber!=null){
              vehicleNumber=vehicleNumber.toUpperCase();
          }*/
          List<Map<String,Object>> vehicle=disVehicleMapper.selectJoinVehicle(platformId,vehicleNumber,vehicleType,enterpriseName,networkState,vehicleLicenseColor);
          for (int i = 0; i < vehicle.size(); i++) {
              Map map=vehicle.get(i);
              String industry=String.valueOf(map.get("industry"));
              String licenseColor=String.valueOf(map.get("vehicleLicenseColor"));
              String vehicleTypeCode=String.valueOf(map.get("vehicleType"));
              String regionCodeId=String.valueOf(map.get("regionCode"));
              String updateDate= String.valueOf(map.get("updateDate"));
              if (updateDate.equals("null")){
                  onlineStatus="离线";
              }else {
                  Date onlineDate=simpleDateFormat.parse(updateDate);
                  if (DateUtils.isSameDay(date,onlineDate)==true){
                      onlineStatus="在线";
                  }else {
                      onlineStatus="离线";
                  }
              }
              //字典表查询行业,车牌颜色
              String vehicleTypeName=disDictionaryMapper.selectVehicleType(vehicleTypeCode);
              String industryName=disDictionaryMapper.selectIndustryId(industry);
              String license=disDictionaryMapper.selectVehicleColor(licenseColor);
              String regionCodeName=tRegionMapper.selectAreaCode(Integer.valueOf(regionCodeId));
              vehicle.get(i).put("industry",industryName);
              vehicle.get(i).put("onlineStatus",onlineStatus);
              vehicle.get(i).put("vehicleLicenseColor",license);
              vehicle.get(i).put("vehicleType",vehicleTypeName);
              vehicle.get(i).put("regionCode",regionCodeName);
          }
              PageInfo pageInfo = new PageInfo(vehicle);
              result = new LayuiTablePagingResult();
              result.setCode(RetCode.SUCCESS.getCode());
              result.setMsg(RetCode.SUCCESS.getMsg());
              result.setCount(pageInfo.getTotal());
              result.setData(pageInfo.getList());
              Long totalPages = pageInfo.getTotal() / size;
              if (pageInfo.getTotal() % size != 0){
                  totalPages ++;
              }
              result.setTotalPages(totalPages);
              return result;
      }catch (Exception e){
          e.printStackTrace();
      }
      return result;
    }


    @ApiOperation(value = "车辆详情展示接口")
    @RequestMapping(value = "/Detail",method = RequestMethod.GET)
    public Response getDetail(Integer vehicleId){
       Response response=new Response();
       try {
           List<Map<String,Object>>vehicleDetail=tDisVehicleMapper.selectDetail(vehicleId);
           Map map=vehicleDetail.get(0);
           String industry=String.valueOf(map.get("industry"));
           String licenseColor=String.valueOf(map.get("vehicleLicenseColor"));
           String vehicleType=String.valueOf(map.get("vehicleType"));
           //字典表查询行业,车牌颜色
           String industryName=disDictionaryMapper.selectIndustryId(industry);
           String license=disDictionaryMapper.selectVehicleColor(licenseColor);
           String vehicleTypeName=disDictionaryMapper.selectVehicleType(vehicleType);
           vehicleDetail.get(0).put("industryName",industryName);
           vehicleDetail.get(0).put("vehicleLicenseColorName",license);
           vehicleDetail.get(0).put("vehicleTypeName",vehicleTypeName);
           response.setCode(RetCode.SUCCESS);
           response.setData(vehicleDetail);
           response.setMsg("执行成功");
       }catch (Exception e){
           e.printStackTrace();
       }
       return response;
    }



    @ApiOperation(value = "首页车辆信息展示")
    @RequestMapping(value = "/vehicleSum",method = RequestMethod.GET)
    public Response getVehicleSum(Integer regionCode,Integer level){
        Response response=new Response();
        try {
            Integer areaCode=null;
            TRegion region =tRegionMapper.selectTRegion(regionCode);
            if (region.getLevel()==1){
                areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,2));
            }else if (region.getLevel()==2){
                areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,4));
            }else if (region.getLevel()==3){
                areaCode= regionCode;
            }
            //查询班车客运的车辆数
            int regularBus=tDisVehicleMapper.selectRegularBus(areaCode);
            //查询包车客运的车辆数
            int charteredBus=tDisVehicleMapper.selectCharteredBus(areaCode);
            //查询危货运输的车辆数
            int DangerousGoods=tDisVehicleMapper.selectDangerousGoods(areaCode);
            HashMap<String,Object>map=new HashMap<>();
            map.put("班车客运",regularBus);
            map.put("包车客运",charteredBus);
            map.put("危货运输",DangerousGoods);
            response.setData(map);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }

        return response;
    }


    @ApiOperation(value = "首页业户信息展示(查询本平台的业户数量)")
    @RequestMapping(value = "/enterpriseSum",method = RequestMethod.GET)
    public Response getEnterprise(Integer level,Integer regionCode){
        Response response=new Response();
        try {
            Integer areaCode=null;
            if (level==1){
                areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,2));
            }else if (level==2){
                areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,4));
            }else if (level==3){
                areaCode= regionCode;
            }
            //接入平台数
            int JoinPlatformSum=tDisPlatformMapper.selectJoinPlatformCount();
            //接入业户数
            int EnterpriseCount=tDisEnterpriseMapper.selectEnterpriseCount(areaCode);
            //拥有班车客运的本平台业户数
            int RegularEnterprise=tDisEnterpriseMapper.selectRegularEnterprise(areaCode);
            //拥有包车客运的本平台业户数
            int CharteredEnterprise=tDisEnterpriseMapper.selectCharteredEnterprise(areaCode);
            //拥有危货运输的本平台业户数
            int DangerousGoodsEnterprise=tDisEnterpriseMapper.selectDangerousGoodsEnterprise(areaCode);
            HashMap<String,Object>map=new HashMap<>();
            map.put("接入平台数",JoinPlatformSum);
            map.put("接入业户数",EnterpriseCount);
            map.put("班车客运",RegularEnterprise);
            map.put("包车客运",CharteredEnterprise);
            map.put("危货运输",DangerousGoodsEnterprise);
            response.setCode(RetCode.SUCCESS);
            response.setData(map);
            response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }



    /*
    * bounds:地图范围区间,range:屏幕范围区间,zoom:比例尺,centerPoint:中心点坐标,radius:聚合半径,organizationId:登录用户所属的机构id
    * */
    @ApiOperation(value = "车辆最新位置聚合查询接口")
    @RequestMapping(value = "/location/cluster",method = RequestMethod.POST,headers = "Accept=application/json")
    public JSONObject getCluster(EncapsulationCluster cluster,Integer regionId,Integer level){
        try {
            //List vehicleIds= carService.selectPlatformIds(platformId);
            //表示响应的内容区数据的媒体类型为json格式，且编码为utf-8(客户端应该以utf-8解码)
            String path = "/dis/vehicle/cluster";
            Map map=new HashMap();
            Integer regionCode=null;
            if (level==1){
                regionCode= Integer.valueOf(String.valueOf(regionId).substring(0,2));
            }else if (level==2){
                regionCode= Integer.valueOf(String.valueOf(regionId).substring(0,4));
            }else if (level==3){
                regionCode= regionId;
            }
/*            map.put("bounds",bounds);//必选 地图范围区间,地理区间范围
            map.put("range",range);//必选 屏幕范围区间,宽，高，单位是像素
            map.put("zoom",zoom);//必选 比例尺地图缩放级别,取值范围1-14
            map.put("centerPoint",centerPoint);//必选 中心点坐标,经度，纬度
            map.put("radius",radius);//必选 聚合半径，单位m，取值是正整数
            map.put("organizationId",String.valueOf(organizationId));//必选 登录用户所属的机构id*/

            String idlist=new String();
            String vehicleId=disVehicleMapper.selectVehicleIdList(regionCode);
            cluster.setVehicleIds(vehicleId);
            JSONObject jsonObject = new JSONObject();
            String body=jsonObject.toJSONString(cluster);//请求体参数 必选 车辆id集合，多个id以英文逗号分隔
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String result=HttpClientUtils.doPostTestThree(path,headMap, map,body);
            JSONObject json= JSONObject.parseObject(result);
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "车辆最新位置查询(车牌号)")
    @RequestMapping(value = "/position/last_location_vn",method = RequestMethod.GET)
    public JSONObject getLastLocationVn(String vehicleNumber){
        Map map=new HashMap();
        map.put("vns",vehicleNumber);
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);//必传 车牌号，多个车牌号以英文逗号分隔
        String url="http://"+Ip+":"+port+"/dis/vehicle/position/last_location_vn";
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }


    @ApiOperation(value = "车辆最新位置查询(sim号)")
    @RequestMapping(value = "/position/last_location_sim",method =RequestMethod.GET)
    public JSONObject getLastLocationSim(String sim){
        Map map=new HashMap();
        map.put("sims",sim);//必传 sim卡号，11位手机号或14位物联网卡号，多个sim卡号以逗号分隔
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/vehicle/position/last_location_sim";
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        Integer platformId=Integer.parseInt(jo.getString("platformId"));//所属平台ID
        Integer vehicleId=Integer.parseInt(jo.getString("vehicleId"));//车辆ID
        String realtimAdminCode=jo.getString("realtimAdminCode");//实施行政区划码
        //String platformName=sysUserService.selectBypId(platformId);//平台名称
        String platformName=tDisPlatformMapper.selectpId(platformId);
        //String vehicleName=pwVehicleMapper.selectByVid(vehicleId);//车辆名称
        String vehicleName=tDisVehicleMapper.selectByVid(vehicleId);
        String areaCodeName=tRegionMapper.selectAreaCodeName(Integer.valueOf(realtimAdminCode));
        json.put("platformName",platformName);
        json.put("vehicleName",vehicleName);
        json.put("areaCodeName",areaCodeName);
        return json;
    }



    @ApiOperation(value = "车辆最新位置查询(车辆id)")
    @RequestMapping(value = "/position/last_location_id",method = RequestMethod.GET)
    public JSONObject getLastLocationId(String vIds){
        Map map=new HashMap();
        map.put("vids",vIds);//必传 车辆id，多个id以英文逗号分隔
        String url="http://"+Ip+":"+port+"/dis/vehicle/position/last_location_id";
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        //JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vehicleId=Integer.parseInt(jsonObject.getString("vehicleId"));//车辆ID
            List<Map<String, Object>>vehicleList=tDisVehicleMapper.selectDetail(vehicleId);
            String regionCodeName=tRegionMapper.selectAreaCode(Integer.parseInt(String.valueOf(vehicleList.get(0).get("regionCode"))));
            List<Map<String,Object>>enterpriseList=tDisEnterpriseMapper.selectByEidList(Integer.valueOf(String.valueOf(vehicleList.get(0).get("enterpriseId"))));
            String scope= String.valueOf(enterpriseList.get(0).get("scope"));

            String industryId=jsonObject.getString("industryId");//所属行业
            Integer realtimAdminCode= Integer.valueOf(jsonObject.getString("realtimeAdminCode"));//实施行政区划码
            String idcard= jsonObject.getString("idcard");//驾驶员姓名
            TDisStaff driverList=tDisStaffMapper.selectByName(idcard);
            String industryName=disDictionaryMapper.selectByItemValue(industryId);
            List<Map<String,Object>>platform=tDisPlatformMapper.selectByPlatformId(Integer.valueOf(String.valueOf(vehicleList.get(0).get("platformId"))));
            if (platform.size()>0){
                jsonObject.put("platformType",platform.get(0).get("platformType"));
                jsonObject.put("linkman",platform.get(0).get("linkman"));
                jsonObject.put("accessCode",platform.get(0).get("accessCode"));
                jsonObject.put("aTestBatch",platform.get(0).get("aTestBatch"));
                jsonObject.put("platformIp",platform.get(0).get("platformIp"));
            }else {
                jsonObject.put("platformType",null);
                jsonObject.put("linkman",null);
                jsonObject.put("accessCode",null);
                jsonObject.put("aTestBatch",null);
                jsonObject.put("platformIp",null);
            }
            jsonObject.put("industryName",industryName);
            jsonObject.put("organizationName",vehicleList.get(0).get("administrationOrgniaztionName"));
            jsonObject.put("attributionArea",regionCodeName);
            if (driverList==null){
                jsonObject.put("idCard",null);
                jsonObject.put("certificateCode",null);
                jsonObject.put("issueOrgan",null);
            }else {
                jsonObject.put("idCard",driverList.getIdcard());
                jsonObject.put("certificateCode",driverList.getCertificateCode());
                jsonObject.put("issueOrgan",driverList.getIssueOrgan());
            }

            jsonObject.put("scope",scope);
        }

        return json;
    }



    @ApiOperation(value = "车辆追踪，根据车辆id查询车辆最新位置，定时调用")
    @RequestMapping(value = "/vehicle_track",method = RequestMethod.GET)
    public JSONObject getVehicleTrack(Integer vId){
        Map map=new HashMap();
        map.put("vid",String.valueOf(vId));//必传 车辆id
        String url="http://"+Ip+":"+port+"/dis/vehicle/position/vehicle_track";
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }


    /*
    * monitorTel:回拨电话号码
    * */
    @ApiOperation(value = "请求车辆监听(单向监听)")
    @MyLog(value = "请求车辆监听(单向监听)")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/listen",method = RequestMethod.POST)
    public JSONObject getListen(Integer platformId,Integer vehicleId,String monitorTel,HttpServletRequest request){
        String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        String newToken=authHeader.replaceAll("Bearer ","");
        String accountNumber=JwtTokenUtil.getUsername(newToken,"MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=");
        CommonUser userMessageList=pwUserMapper.selectUserAndRole(accountNumber);
        Integer  areaCode=Integer.parseInt(String.valueOf(userMessageList.getRegionCode()));
        Integer  level=Integer.parseInt(String.valueOf(userMessageList.getLevel()));
        Integer  roleType=Integer.parseInt(String.valueOf(userMessageList.getRoleType()));
        if (roleType!=1){
            String list = "{\"code\":1009,\"msg\":\"此账号为监管员账号,不可进行操作\"}";
            return JSONObject.parseObject(list);
        }
      Map map=new HashMap();
      map.put("platformId",String.valueOf(platformId));//必传 平台id
        map.put("vehicleId",String.valueOf(vehicleId));//必传 车辆id
         map.put("monitorTel",monitorTel);//必传 回拨电话
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
      String url="http://"+Ip+":"+port+"/dis/v1/platform/listen";
      String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }


    /*
    *result为结果标识 0 监听成功  1 监听失败
    * */
    @ApiOperation(value = "车辆监听回调接口--(待定保留)")
    @RequestMapping(value = "/listen/result",method = RequestMethod.POST)
    @JwtIgnore
    public Response getCallback(Integer platformId,String answerTime,Integer vehicleId,Integer result){
        Response response=new Response();

        return response;
    }


    /*
    * lensId:镜头id
    * size:照片大小定义
    * */
    @ApiOperation(value = "车辆拍照接口--废弃")
    @RequestMapping(value = "/takePhoto",method = RequestMethod.POST)
    public JSONObject getTakePhoto(Integer platformId,Integer vehicleId,Integer lensId,String size){

        Map map=new HashMap();
        map.put("platformId",platformId);
        map.put("vehicleId",vehicleId);
        map.put("lensId",lensId);
        map.put("size",size);
        String url="http://"+Ip+":"+port+"/dis/v1/platform/sendPacket";
        String result=HttpClientUtil.doPost(url,map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
        }



       //=============车辆拍照接口回调==============
       /*
       * result为结果标识 0 不支持拍照  1 完成拍照 2完成拍照照片稍后传输
3未拍照（不在线）4未拍照（无法使用指定摄像头）5未拍照（其他原因）
6车牌号码错误 ,type为图像格式定义如下 1 jpg 2 gif  3 tiff  4 png
photo 为图片的16进制字符串 accFlag:acc 状态 0 关闭    1 开启
       * */
       @ApiOperation(value = "车辆拍照接口回调")
       @RequestMapping(value = "/activeSafety/download_response",method = RequestMethod.POST)
       @JwtIgnore
       public void getTakePhotoCallback(HttpServletRequest request,String base64,Integer vehicleId,Integer channelId,String photo_rsp_flag,String platformCode,String type,String accFlag,Integer v1,Integer v2){
           Long pictureName=System.currentTimeMillis();
           if (base64==null){
               log.info("此信息照片为null");
               return;
           }
           String format=type.equals("1")?"jpg":type.equals("2")?"gif":type.equals("3")?"tiff":type.equals("4")?"png":"jpg";
           String photo=base64.replaceAll(" ", "+");
           boolean s=Base64s.Base64ToImage(photo,imagePath+pictureName+"."+format);
           String path=imageServerBaseUrl+pictureName+".jpg";//图片地址
           List<Map> vehicleList=tDisVehicleMapper.selectVnameAndColor(vehicleId);
           String vehicleNumber="";
           if (vehicleList.size()==0 || vehicleList.size()>1){
               vehicleNumber= "null";
           }else {
               vehicleNumber= String.valueOf(vehicleList.get(0).get("vehicle_number"));
           }
           if (s==true){
               pwImagePath imagePath=new pwImagePath();
               imagePath.setChannelId(channelId);
               imagePath.setImagePath(path);
               imagePath.setPhotoRspFlag(photo_rsp_flag);
               imagePath.setVehicleId(vehicleId);
               imagePath.setPlatformCode(platformCode);
               imagePath.setAccFlag(accFlag);
               imagePath.setV1(v1);
               imagePath.setV2(v2);
               imagePath.setVehicleNumber(vehicleNumber);
               int i=imagePathMapper.insertSelective(imagePath);
               log.info("车辆拍照回调成功");
           }else {
               pwImagePath imagePath=new pwImagePath();
               imagePath.setChannelId(channelId);
               imagePath.setImagePath(path);
               imagePath.setPhotoRspFlag(photo_rsp_flag);
               imagePath.setVehicleId(vehicleId);
               imagePath.setPlatformCode(platformCode);
               imagePath.setAccFlag(accFlag);
               imagePath.setV1(v1);
               imagePath.setV2(v2);
               imagePath.setVehicleNumber(vehicleNumber);
               int i=imagePathMapper.insertSelective(imagePath);
               log.info("车辆拍照回调失败");
           }
       }

       @ApiOperation(value = "根据平台code展示拍照回调图片展示")
       @RequestMapping(value = "/showImage",method = RequestMethod.GET)
       public LayuiTablePagingResult showImage(Integer page, Integer size,  String vehicleNumber,String photoRspFlag,String startTime,String endTime){
         LayuiTablePagingResult result=null;
         try {
             PageHelper.startPage(page,size);
             if (vehicleNumber!=null && vehicleNumber.length() < 3) {
                 result = new LayuiTablePagingResult();
                 result.setCode("1009");
                 result.setMsg("请输入车牌号不少于3位");
                 result.setCount(Long.valueOf(0));
                 result.setData(0);
                 return result;
             }
             if (vehicleNumber!=null){
                 vehicleNumber=vehicleNumber.toUpperCase();
             }
             List<Map<String,Object>>imageList=imagePathMapper.selectImage(vehicleNumber,photoRspFlag,startTime,endTime);
             PageInfo pageInfo=new PageInfo<>(imageList);
             result = new LayuiTablePagingResult();
             result.setCode(RetCode.SUCCESS.getCode());
             result.setMsg(RetCode.SUCCESS.getMsg());
             result.setCount(pageInfo.getTotal());
             result.setData(pageInfo.getList());
             Long totalPages = pageInfo.getTotal() / size;
             if (pageInfo.getTotal() % size != 0){
                 totalPages ++;
             }
             result.setTotalPages(totalPages);
         }catch (Exception e){
             e.printStackTrace();
         }
           return result;
       }


       @ApiOperation(value = "车辆应急接入监管平台接口")
       @MyLog(value = "车辆应急接入监管平台")  //这里添加了AOP的自定义注解
       @RequestMapping(value = "/emergency",method = RequestMethod.POST)
       public JSONObject getEmergency(String platformId, String vehicleId, String authCode, String accessPointName, String username, String password, String serverIp, String tcpPort, String udpPort, String endTime,HttpServletRequest request){
           Boolean flag=listerUtil.getRoleType(request);
           if (flag==false){
               String list = "{\"code\":1009,\"msg\":\"此账号为监管员账号,不可进行操作\"}";
               return JSONObject.parseObject(list);
           }
           Map map=new HashMap();
           map.put("platformId",platformId);//必选
           map.put("vehicleId",vehicleId);//必选 车辆id
           map.put("authCode",authCode);//必选 用于车辆鉴权码
           map.put("accessPointName",accessPointName);//必选 拨号点名称一般为服务器APN
           map.put("username",username);//必选 拨号用户名
           map.put("password",password);//必选 拨号密码
           map.put("serverIp",serverIp);//必选 服务器IP地址
           map.put("tcpPort",tcpPort);//必选 tcp端口
           map.put("udpPort",udpPort);//必选 udp端口
           map.put("endTime",endTime);//必选 结束时间 0表示一直连接
           Map<String,String>headMap=new HashMap<>();
           headMap.put("clientCode",clientCode);
           String url="http://"+Ip+":"+port+"/dis/v1/platform/emergency";
           String result=HttpClientUtils.doPost(url,headMap,map);
           JSONObject json= JSONObject.parseObject(result);
           log.info(result);
           return json;
       }


       //============车辆应急接入监管平台回调接口========
    /*
    * result为结果标识 0 车辆成功收到该命令  1 无该车辆  2其他原因失败
     * */
       @ApiOperation(value = "车辆应急接入监管平台回调接口")
       @RequestMapping(value = "/emergency/result",method = RequestMethod.POST)
       @JwtIgnore
       public Response getEmergency(Integer platformId,String answerTime,Integer vehicleId,String result){
           Response response=new Response();
           String vehicleName=tDisVehicleMapper.selectByVid(vehicleId);
           String platformName=tDisPlatformMapper.selectpId(platformId);
           Map map=new HashMap();
           map.put("vehicleId",vehicleId);
           map.put("vehicleName",vehicleName);
           map.put("platformName",platformName);
           map.put("answerTime",answerTime);
           map.put("result",result);
           response.setData(map);
           response.setCode(RetCode.SUCCESS);
           response.setMsg("执行成功");
           return response;
       }


    @ApiOperation(value = "上报车辆注册信息接口（回调接口)")
    @RequestMapping(value = "/reportRegisterInfo",method = RequestMethod.POST)
    @JwtIgnore
    public Response reportRegisterInfo(Integer platformId,Integer vehicleId,String produceId,String terminalModelType,String terminalId,String sim){
        Response response=new Response();
        Map map=new HashMap();
        map.put("platformId",platformId);
        map.put("vehicleId",vehicleId);
        return response;
    }

    @ApiOperation(value = "车辆注册接口")
    @RequestMapping(value = "/registerList",method = RequestMethod.GET)
    public JSONObject getRegisterList(String vNumber,String regionCode,String limit,String page,String startTime,String endTime) {
        if (vNumber!=null && vNumber.length() < 3) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        } else {
            Map map = new HashMap();
            if (vNumber!=null){
                vNumber=vNumber.toUpperCase();
            }
            map.put("vnumber", vNumber);//车牌号
            map.put("regionCode", regionCode);//必选 行政区域编号
            map.put("limit", limit);//必传 页面记录数，默认为10
            map.put("page", page);//必传 页码，默认为1
     /*       map.put("startTime", startTime); //开始查询时间yyyy-MM-dd HH:mm:ss
            map.put("endTime", endTime);  //结束查询时间yyyy-MM-dd HH:mm:ss*/
            Set<String> set = map.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String str = it.next();
                if (map.get(str) == null || map.get(str) == "null" || map.get(str) == "") {
                    map.remove(str);
                    set = map.keySet();
                    it = set.iterator();
                }
            }
            Map<String, String> headMap = new HashMap<>();
            headMap.put("clientCode", clientCode);
            String url = "http://" + Ip + ":" + port + "/dis/business/vehicle/registerList";
            String result = HttpClientUtils.doGet(url, headMap, map);
            JSONObject json = JSONObject.parseObject(result);
            JSONObject jo = json.getJSONObject("result");
            JSONArray jsonArray = jo.getJSONArray("list");
            if (jsonArray == null) {
                return json;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Integer vehicelId = Integer.parseInt(jsonObject.getString("vehicleId"));//车辆id
                String vehicelColor = jsonObject.getString("color");//车牌颜色
                String region = jsonObject.getString("regionCode");//所属地区
                String regionCodeName = tRegionMapper.selectAreaCode(Integer.valueOf(region));
                String vehicleLicenseColor = disDictionaryMapper.selectVehicleColor(vehicelColor);//车牌颜色
                List<Map<String, Object>> vehicle = tDisVehicleMapper.selectDetail(vehicelId);
                jsonObject.put("vehicleNumber", vehicle.get(0).get("vehicleNumber"));
                jsonObject.put("vehicleLicenseColor", vehicleLicenseColor);
                jsonObject.put("regionCodeName", regionCodeName);
                jsonObject.put("sim", vehicle.get(0).get("sim"));
            }
            return json;
        }
    }


    @ApiOperation(value = "凌晨2点到5点违规运行明细接口")
    @RequestMapping(value = "/illegalrun",method = RequestMethod.GET)
    public JSONObject getIllegalrun(String nanos,String startTime,String endTime,String regionCode,String pageSize,String pageNum,String eName,String pName,String vNumber){
        String eIdsList="";
        String vIdlist="";
        String pIdList="";
        String eIds=null;
        String vIds=null;
        String pIds=null;
        if (eName!=null && eName.equals("")==false){
            List<Map> eIdsLists = tDisEnterpriseMapper.selectEnterpriseNameList(eName);
            if (eIdsLists.size()>0){
                for (int i = 0; i < eIdsLists.size(); i++) {
                    eIdsList = eIdsList + eIdsLists.get(i).get("enterprise_id")+",";
                }
                eIds=StringUtils.join(eIdsList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber);
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (pName!=null && pName.equals("")==false){
            List<Map> pIdsList=tDisPlatformMapper.selectPlatformIdsList(pName);


            if (pIdsList.size()>0){
                for (int i = 0; i < pIdsList.size(); i++) {
                    pIdList=pIdList+pIdsList.get(i).get("platform_id")+",";
                }
                pIds=StringUtils.join(pIdList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        map.put("enterpriseId",eIds);//企业id
        map.put("nanos",nanos);
        map.put("platformId",pIds);//平台id
        map.put("vehicleId",vIds);//车辆id
        map.put("startTime",startTime);//必选 开始时间 yyyy-mm-dd hh:mm:ss,开始结束和结束时间间隔不能超过3天
        map.put("endTime",endTime);//必选 yyyy-mm-dd hh:mm:ss, 结束时间
        map.put("pageNum",pageNum);//必选 页码
        map.put("pageSize",pageSize);//必选 页面记录条数
        map.put("regionCode",regionCode);//必选 登录用户所属的机构所在地区行政区划代码
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/track/illegalrun";
        String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer pId=Integer.parseInt(jsonObject.getString("platformId"));//平台id
            Integer eId=Integer.parseInt(jsonObject.getString("enterpriseId"));//企业id
            //String enterpriseName=sysEnterpriseMapper.selectByEid(eId);//企业名称
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eId);
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("platformName",platformName);
        }
        return json;
    }


    @ApiOperation(value = "末次位置统计")
    @RequestMapping(value = "/lastposition",method = RequestMethod.GET)
    public JSONObject lastposition(String vehicles){
           Map map=new HashMap();
           map.put("vids",vehicles);//必选 车辆id，多个id以英文逗号分隔
           String url="http://"+Ip+":"+port+"/dis/v1/track/lastposition";
           Map<String,String>headMap=new HashMap<>();
           headMap.put("clientCode",clientCode);
           String result=HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer pId=Integer.parseInt(jsonObject.getString("platformId"));//平台id
            Integer eId=Integer.parseInt(jsonObject.getString("enterpriseId"));//企业id
            Integer vId=Integer.parseInt(jsonObject.getString("vehicleId"));//车辆id
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eId);
            String platformName=tDisPlatformMapper.selectpId(pId);
            String vehicleNumber=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("vehicleNumber",vehicleNumber);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("platformName",platformName);
        }
           return json;
    }



    /*
     * organizationId:登录用户所属的机构id
     *
     * */
    @ApiOperation(value = "车辆动态综合统计")
    @RequestMapping(value = "/dynamic",method = RequestMethod.POST)
    public JSONObject getDynamic(String date,String industryIds,String limit,String page,String eid,String pName,String vNumber){
        if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        }
        String vIdlist="";
        String pIdList="";
        String vIds=null;
        String pIds=null;
        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber.toUpperCase());
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (pName!=null && pName.equals("")==false){
            List<Map> pIdsList=tDisPlatformMapper.selectPlatformIdsList(pName);
            if (pIdsList.size()>0){
                for (int i = 0; i < pIdsList.size(); i++) {
                    pIdList=pIdList+pIdsList.get(i).get("platform_id")+",";
                }
                pIds=StringUtils.join(pIdList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        String s = date.replaceAll("-", "");
        map.put("date",s);// 必选 查询日期yyyymmdd
        map.put("vids",vIds);//车辆id,多个id以逗号分隔
        map.put("eids",eid);//企业id,多个id以逗号分隔
        map.put("industryIds",industryIds);//行业id,多个id以逗号分隔
        map.put("pids",pIds);//平台id,多个id以逗号分隔
        map.put("limit",limit);//页面记录数，默认为10
        map.put("page",page);//页码，默认为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistic/vehicle/dynamic";
        String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            Integer eIds=Integer.parseInt(jsonObject.getString("eId"));//企业id
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Double passRate=Double.valueOf(jsonObject.getString("passRate"));//数据合格率
            passRate=passRate*100;
            //String enterpriseName=sysEnterpriseMapper.selectByEid(eId);//企业名称
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eIds);
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            //String vehicleNumber=pwVehicleMapper.selectByVid(vId);//车辆名称
            List<Map<String,Object>>vehicle=tDisVehicleMapper.selectVehicle(vId);
            String vehicleLicenseColor=null;
            String vehicleNumber=null;
            if (vehicle.size()>0){
                vehicleLicenseColor=String.valueOf(vehicle.get(0).get("item_name"));//车牌颜色
                vehicleNumber=String.valueOf(vehicle.get(0).get("vehicle_number"));
            }
            jsonObject.put("vehicleNumber",vehicleNumber);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("platformName",platformName);
            jsonObject.put("passRate",String.valueOf(passRate)+"%");
            jsonObject.put("vehicleLicenseColor",vehicleLicenseColor);
        }
        return json;
    }



    @ApiOperation(value = "车辆动态情况统计")
    @RequestMapping(value = "/dynamicSituationStatistic",method = RequestMethod.POST)
    public JSONObject dynamicSituationStatistic(String date,String vids,String eids,String industryIds,String pids,String limit,String page){

        NumberFormat nf = java.text.NumberFormat.getPercentInstance();
        Map map=new HashMap();
        String s = date.replaceAll("-", "");
        map.put("date",s);//必传 查询日期yyyymmdd
        map.put("vids",vids);//车辆id,多个id以逗号分隔
        map.put("eids",eids);//企业id,多个id以逗号分隔
        map.put("industryIds",industryIds);//行政区划代码，多个逗号分隔
        map.put("limit",limit);//页面记录数，默认为10
        map.put("page",page);//页码，默认为1
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistic/vehicle/dynamic";
        String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            Integer eId=Integer.parseInt(jsonObject.getString("eId"));//企业id
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id

            String passRate=jsonObject.getString("passRate");//数据正确率
            double c=Double.valueOf(passRate);
            String passRates=nf.format(c);//将数据正确率转成百分数

            String trackFullRate=jsonObject.getString("trackFullRate");//轨迹完成率
            double track=Double.valueOf(trackFullRate);
            String trackFullRates=nf.format(track);//将轨迹完成率转成百分数

            Integer onlineTime=Integer.parseInt(jsonObject.getString("onlineTime"));//在线时长(min)
            double onlineTimes = new BigDecimal((float)onlineTime/60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            //String enterpriseName=sysEnterpriseMapper.selectByEid(eId);//企业名称
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eId);
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            //String vehicleNumber=pwVehicleMapper.selectByVid(vId);//车辆名称
            String vehicleNumber=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("vehicleNumber",vehicleNumber);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("platformName",platformName);
            jsonObject.put("onlineTime",String.valueOf(onlineTimes));
        }
        return json;
    }

    @ApiOperation(value = "驾驶员信息详情")
    @RequestMapping(value = "/driverDetails",method = RequestMethod.GET)
    public Response getDriverDetails(String driverName){
        Response response=new Response();
        TDisStaff tDisStaff =tDisStaffMapper.selectDriverDetail(driverName);
        response.setData(tDisStaff);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }



    @ApiOperation(value = "车辆行驶路线添加(1:行驶路线2:行驶区域)")
    @RequestMapping(value = "/pathAdd",method = RequestMethod.POST)
    public Response pathAdd(@RequestBody pwVehiclePath pwVehiclePath, HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            int i =pwVehiclePathMapper.insertSelective(pwVehiclePath);
            Map map=new HashMap();
            //位置平台围栏ID
            map.put("fenceId",String.valueOf(pwVehiclePath.getPathId()));
            //围栏名称
            map.put("name",pwVehiclePath.getPathName());
            //围栏类型，0 线路围栏 1 矩形 2 圆形 3 多边形 4 涵洞 5 隧道 6高速公路
            map.put("type",String.valueOf(pwVehiclePath.getType()));
            //半径，取值范围为0到5000，单位米，只能为整数,type为2时有效
            map.put("radius",String.valueOf(pwVehiclePath.getRadius()));
            //描述，长度范围为0到100
            map.put("description",pwVehiclePath.getDescription());
            //生效日期
            map.put("validTime",String.valueOf(pwVehiclePath.getEffectiveTime()));
            //失效日期
            map.put("expireTime",String.valueOf(pwVehiclePath.getFailureTime()));
            //圆心经纬度 ,type为2时有效，字符串 例如 经度,纬度 12,456
            map.put("center",pwVehiclePath.getCenter());
            //驶入车辆限制,取值范围为0到100000,不填表示无限制
            map.put("vehicleLimit",String.valueOf(pwVehiclePath.getOverCapacity()));
            //限速,取值范围为0到240，单位km/h,不填表示无限速
            map.put("speedLimit",String.valueOf(pwVehiclePath.getRateLimiting()));
            //驶入驶出标志 0 无报警 1 驶入需报警 2 驶出需报警 3 驶入驶出都需报警
            map.put("warnFlag",pwVehiclePath.getEnterIntoAlarm());
            //矩形左上经纬度 ， type为1时有效,经纬度英文逗号分隔,如经度,纬度
            map.put("squareLeft",pwVehiclePath.getSquareLeft());
            //矩形右下经纬度 ， type为1时有效,经纬度英文逗号分隔,如经度,纬度
            map.put("squareRight",pwVehiclePath.getSquareRight());
            //多边形顶点经纬度， type为3时有效，每个顶点经纬度用分号分隔 如 12,23;12,23
            map.put("polygonVerticles",pwVehiclePath.getPolygonVerticles());
            //路宽,type为5时有效,取值范围为0到500，单位为米
            map.put("roadWidth",String.valueOf(pwVehiclePath.getRoadWidth()));
            //路线拐点经纬度,type为5时有效,经纬度以英文逗号分隔
            map.put("roadTurnVerticles",pwVehiclePath.getRoadTurnVerticles());
            //上层业务系统传送的机构id
            map.put("organizationId",String.valueOf(pwVehiclePath.getOrganizationId()));
            Set<String> set = map.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String str = it.next();
                if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                    map.remove(str);
                    set = map.keySet();
                    it = set.iterator();
                }
            }
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String url="http://"+Ip+":"+port+"/dis/v1/fence/area";
            String result=HttpClientUtils.doPost(url,headMap,map);
            log.info(result);
            response.setData(pwVehiclePath.getPathId());
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
        }catch (DuplicateKeyException Exception){
            Exception.printStackTrace();
            response.setCode(RetCode.REQUEST_ERROR);
            response.setMsg("线路/区域名称不能重复");
            return response;
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;

    }

    @ApiOperation(value = "围栏绑定车辆，每次修改绑定关系，需将所有绑定车辆id传递到接口")
    @RequestMapping(value = "/bind",method = RequestMethod.POST)
    public Response getBind(Integer fenceId,String vehicleIds,HttpServletRequest request){
        Response response=new Response();
        Boolean flag=listerUtil.getRoleType(request);
        if (flag==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("此账号为监管员账号,不可进行操作");
            return response;
        }
        Map map=new HashMap();
        map.put("fenceId",String.valueOf(fenceId));//必传 围栏id，int
        map.put("vehicleIds",vehicleIds);//绑定的车辆id，多个id以英文逗号分隔
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/fence/bind";
        String result=HttpClientUtils.doPost(url,headMap,map);
        log.info(result);
        pwVehiclePath pwVehiclePath=new pwVehiclePath();
        pwVehiclePath.setPathId(fenceId);
        pwVehiclePath.setVehicleId(vehicleIds);
        pwVehiclePathMapper.updateByPrimaryKeySelective(pwVehiclePath);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }



    @ApiOperation(value = "地区车牌号展示")
    @RequestMapping(value = "/ShowVehicleNumber",method = RequestMethod.GET)
    public Response getShowVehicleNumber(String enterpriseId){
        Response response=new Response();
        String[] eIdList=enterpriseId.split(",");
        ArrayList list=new ArrayList();
        List<Map<String,Object>>vehicleNumber=new ArrayList<>();
        for (String eId : eIdList) {
            vehicleNumber=tDisVehicleMapper.selectVehicleNumber(Integer.valueOf(eId));
            list.add(vehicleNumber);
        }
        response.setData(list);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "业户信息(根据所属地)")
    @RequestMapping(value = "/EnterpriseRegionCode",method = RequestMethod.GET)
    public Response getEnterpriseRegionCode(Integer regionCode,Integer level){
        Response response=new Response();
        Integer areaCode=null;
        if (level==1){
            areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,2));
        }else if (level==2){
            areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,4));
        }else if (level==3){
            areaCode= regionCode;
        }
        List<Map>enterpriseIdList=tDisEnterpriseMapper.selectEnterpriseId(areaCode);
        response.setData(enterpriseIdList);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return  response;
    }

    @ApiOperation(value = "车辆行驶路线(展示单个)")
    @RequestMapping(value = "/pathShow",method = RequestMethod.GET)
    public Response pathShow(Integer pathId){
        Response response=new Response();
        Map pwVehiclePath=pwVehiclePathMapper.selectByPrimaryKey(pathId);
        Map vehicleMap=new HashMap();
        List<Map> list=new ArrayList<>();
        list.add(vehicleMap);
        vehicleMap.put("pwVehiclePath",pwVehiclePath);
        if (pwVehiclePath.get("vehicleId")!=null) {
            String[] vehicleName = String.valueOf(pwVehiclePath.get("vehicleId")).split(",");
            String[] vehicleAndID;
            for (String vId : vehicleName) {
                String vIdName = disVehicleMapper.selectByVid(Integer.parseInt(vId));
                Map map = new HashMap();
                map.put("vehicleId", vId);
                map.put("vehicleNumber", vIdName);
                list.add(map);
            }
        }
        response.setData(list);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }


    @ApiOperation(value = "车辆行驶路线(修改)")
    @RequestMapping(value = "/pathUpdate",method = RequestMethod.POST)
    public Response pathUpdate(@Valid @RequestBody pwVehiclePath pwVehiclePath,HttpServletRequest request){
        Response response=new Response();
        Boolean flag=listerUtil.getRoleType(request);
        if (flag==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("此账号为监管员账号,不可进行操作");
            return response;
        }
        int i=pwVehiclePathMapper.updateByPrimaryKeySelective(pwVehiclePath);
        Map map=new HashMap();
        //位置平台围栏ID
        map.put("fenceId",String.valueOf(pwVehiclePath.getPathId()));
        //围栏名称
        map.put("name",pwVehiclePath.getPathName());
        //围栏类型，0 线路围栏 1 矩形 2 圆形 3 多边形 4 涵洞 5 隧道 6高速公路
        map.put("type",String.valueOf(pwVehiclePath.getType()));
        //半径，取值范围为0到5000，单位米，只能为整数,type为2时有效
        map.put("radius",String.valueOf(pwVehiclePath.getRadius()));
        //描述，长度范围为0到100
        map.put("description",pwVehiclePath.getDescription());
        //生效日期
        map.put("validTime",String.valueOf(pwVehiclePath.getEffectiveTime()));
        //失效日期
        map.put("expireTime",String.valueOf(pwVehiclePath.getFailureTime()));
        //圆心经纬度 ,type为2时有效，字符串 例如 经度,纬度 12,456
        map.put("center",pwVehiclePath.getCenter());
        //驶入车辆限制,取值范围为0到100000,不填表示无限制
        map.put("vehicleLimit",String.valueOf(pwVehiclePath.getOverCapacity()));
        //限速,取值范围为0到240，单位km/h,不填表示无限速
        map.put("speedLimit",String.valueOf(pwVehiclePath.getRateLimiting()));
        //驶入驶出标志 0 无报警 1 驶入需报警 2 驶出需报警 3 驶入驶出都需报警
        map.put("warnFlag",pwVehiclePath.getEnterIntoAlarm());
        //矩形左上经纬度 ， type为1时有效,经纬度英文逗号分隔,如经度,纬度
        map.put("squareLeft",pwVehiclePath.getSquareLeft());
        //矩形右下经纬度 ， type为1时有效,经纬度英文逗号分隔,如经度,纬度
        map.put("squareRight",pwVehiclePath.getSquareRight());
        //多边形顶点经纬度， type为3时有效，每个顶点经纬度用分号分隔 如 12,23;12,23
        map.put("polygonVerticles",pwVehiclePath.getPolygonVerticles());
        //路宽,type为5时有效,取值范围为0到500，单位为米
        map.put("roadWidth",String.valueOf(pwVehiclePath.getRoadWidth()));
        //路线拐点经纬度,type为5时有效,经纬度以英文逗号分隔
        map.put("roadTurnVerticles",pwVehiclePath.getRoadTurnVerticles());
        //上层业务系统传送的机构id
        map.put("organizationId",String.valueOf(pwVehiclePath.getOrganizationId()));
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/fence/area_update";
        String result=HttpClientUtils.doPost(url,headMap,map);
        log.info(result);
        response.setData(pwVehiclePath.getPathId());
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }


    @ApiOperation(value = "车辆行驶路线(删除)")
    @RequestMapping(value = "/pathDelete",method = RequestMethod.POST)
    public Response pathDelete(Integer pathId,HttpServletRequest request){
        Response response=new Response();
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            int i=pwVehiclePathMapper.deleteByPId(pathId);
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String url="http://"+Ip+":"+port+"/dis/v1/fence/area/"+pathId;
            String result=HttpClientUtils.doDelete(url,headMap);
            log.info(result);
            response.setData(i);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    @ApiOperation(value = "车辆行驶路线(展示全部)")
    @RequestMapping(value = "/showAll",method = RequestMethod.GET)
    public LayuiTablePagingResult getAll(Integer page,Integer size,Integer status,String startTime,String endTime,String pathName,HttpServletRequest request){
        LayuiTablePagingResult result=null;
        PageHelper.startPage(page,size);
        String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        String newToken=authHeader.replaceAll("Bearer ","");
        String accountNumber=JwtTokenUtil.getUsername(newToken,"MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=");
        List<Map<String, Object>> userMessageList=pwUserMapper.selectOne(accountNumber);
        int  areaCode=Integer.parseInt(String.valueOf(userMessageList.get(0).get("regionCode")));
        int  level=Integer.parseInt(String.valueOf(userMessageList.get(0).get("level")));
        int  id=Integer.parseInt(String.valueOf(userMessageList.get(0).get("id")));
        Map<String, Integer> map=new HashMap<>();
        map.put("regionCode",areaCode);
        map.put("level",level);
        map.put("id",id);
        Integer uId=map.get("id");
        List<Map<String,Object>>vehiclePathList=pwVehiclePathMapper.selectAll(status,startTime,endTime,pathName,uId);
        PageInfo pageInfo=new PageInfo(vehiclePathList);
        result = new LayuiTablePagingResult();
        result.setCode(RetCode.SUCCESS.getCode());
        result.setMsg(RetCode.SUCCESS.getMsg());
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        Long totalPages = pageInfo.getTotal() / size;
        if (pageInfo.getTotal() % size != 0){
            totalPages ++;
        }
        result.setTotalPages(totalPages);
        return result;
    }



    @ApiOperation(value = "请求交换指定车辆(交换车辆定位信息)")
    @RequestMapping(value = "/applyStart",method = RequestMethod.POST)
    public JSONObject applyStart(String startTime,String endTime,String platformId,String vehicleId,HttpServletRequest request){
        try {
            Boolean flag=listerUtil.getRoleType(request);
            if (flag==false){
                String list = "{\"code\":1009,\"msg\":\"此账号为监管员账号,不可进行操作\"}";
                return JSONObject.parseObject(list);
            }

            Map map=new HashMap();
            map.put("startTime",startTime);//必传 开始时间 YY-MM-DD HH-MM-SS
            map.put("endTime",endTime);//必传 结束时间 YY-MM-DD HH-MM-SS
            map.put("platformId",platformId);//必传 平台id
            map.put("vehicleId",vehicleId);//必传 车辆id
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String url="http://"+Ip+":"+port+"/dis/v1/platform/applyStart";
            String result=HttpClientUtils.doPost(url,headMap,map);
            JSONObject jsonObject= JSONObject.parseObject(result);
            log.info(result);
            return jsonObject;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "请求交换指定车辆(交换车辆定位信息)回调接口")
    @RequestMapping(value = "/applyStart/result",method = RequestMethod.POST)
    @JwtIgnore
    public Response getResult(Integer platformId,String answerTime,Integer vehicleId,Integer result){
        Response response=new Response();
        String platformName=tDisPlatformMapper.selectpId(platformId);
        String vehicleName=tDisVehicleMapper.selectByVid(vehicleId);
        Map map=new HashMap();
        map.put("platformId",platformId);
        map.put("answerTime",answerTime);
        map.put("vehicleId",vehicleId);
        map.put("result",result);
        map.put("vehicleName",vehicleName);
        map.put("platformName",platformName);
        response.setData(map);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        log.info("请求交换指定车辆(交换车辆定位信息)回调成功");
        return response;
    }

    @ApiOperation(value = "请求终止交换指定车辆")
    @RequestMapping(value = "/applyCancel",method = RequestMethod.POST)
    public JSONObject applyCancel(String platformId,String vehicleId,HttpServletRequest request){
         try {
             Boolean flag=listerUtil.getRoleType(request);
             if (flag==false){
                 String list = "{\"code\":1009,\"msg\":\"此账号为监管员账号,不可进行操作\"}";
                 return JSONObject.parseObject(list);
             }
             Map map=new HashMap();
             map.put("platformId",platformId);//必传 平台id
             map.put("vehicleId",vehicleId);//必传 车辆id
             Map<String,String>headMap=new HashMap<>();
             headMap.put("clientCode",clientCode);
             String url="http://"+Ip+":"+port+"/dis/v1/platform/applyCancel";
             String result=HttpClientUtils.doPost(url,headMap,map);
             JSONObject jsonObject= JSONObject.parseObject(result);
             return jsonObject;

         }catch (Exception e){
             e.printStackTrace();
         }
         return null;
    }


    @ApiOperation(value = "根据车辆sim卡号查询指定车辆历史位置")
    @RequestMapping(value = "/track_sim",method = RequestMethod.GET)
    public JSONObject trackSim(String sim,String startTime,String endTime,String pageNum,String pageSize){
        Map map=new HashMap();
        map.put("sim",sim);//必传 车辆sim卡号
        map.put("startTime",startTime);//必传 查询起始时间，开始结束时间跨度限制为24h
        map.put("endTime",endTime);//必传 查询结束时间
        map.put("pageNum",pageNum);//页码
        map.put("pageSize",pageSize);//每页条数
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/vehicle/track_sim";
        String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            //String vehicleName=pwVehicleMapper.selectByVid(vId);//车辆名称
            String vehicleName=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("platformName",platformName);
            jsonObject.put("vehicleName",vehicleName);
        }
        return json;
    }


    @ApiOperation(value = "根据车辆id查询指定车辆历史位置")
    @RequestMapping(value = "/track_vid",method = RequestMethod.GET)
    public JSONObject trackVid(String vehicleId,String startTime,String endTime,String pageNum,String pageSize) {
        Map map = new HashMap();
        map.put("vehicleId", vehicleId);//必传 车辆id
        map.put("startTime", startTime);//必传 查询起始时间，开始结束时间跨度限制为24h
        map.put("endTime", endTime);//必传 查询结束时间
        map.put("pageNum", pageNum);//页码
        map.put("pageSize", pageSize);//每页条数
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if (map.get(str) == null || map.get(str) == "null" || map.get(str) == "") {
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String, String> headMap = new HashMap<>();
        headMap.put("clientCode", clientCode);
        String url = "http://" + Ip + ":" + port + "/dis/vehicle/track_vid";
        String result = HttpClientUtils.doPost(url, headMap, map);
        JSONObject json= JSONObject.parseObject(result);
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            //String vehicleName=pwVehicleMapper.selectByVid(vId);//车辆名称
            String vehicleName=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("platformName",platformName);
            jsonObject.put("vehicleName",vehicleName);
        }
        return json;
    }


    @ApiOperation(value = "根据车辆车牌号查询指定车辆历史位置")
    @RequestMapping(value = "/trackVn",method = RequestMethod.GET)
    public JSONObject trackVn(String vehicleNumber,String startTime,String endTime,String pageNum,String pageSize) {
        Map map = new HashMap();
        map.put("vehicleNumber", vehicleNumber);//必传 车牌号
        map.put("startTime", startTime);//必传 查询起始时间，开始结束时间跨度限制为24h
        map.put("endTime", endTime);//必传 查询结束时间
        map.put("pageNum", pageNum);//页码
        map.put("pageSize", pageSize);//每页条数
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if (map.get(str) == null || map.get(str) == "null" || map.get(str) == "") {
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String, String> headMap = new HashMap<>();
        headMap.put("clientCode", clientCode);
        String url = "http://" + Ip + ":" + port + "/dis/vehicle/trackVn";
        String result = HttpClientUtils.doPost(url, headMap, map);
        JSONObject json= JSONObject.parseObject(result);
        JSONArray jsonArray=json.getJSONArray("result");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Integer pId=Integer.parseInt(jsonObject.getString("pId"));//平台id
            //String platformName=sysUserService.selectBypId(pId);//平台名称
            String platformName=tDisPlatformMapper.selectpId(pId);
            //String vehicleName=pwVehicleMapper.selectByVid(vId);//车辆名称
            String vehicleName=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("platformName",platformName);
            jsonObject.put("vehicleName",vehicleName);
        };
        return json;
    }


    @ApiOperation(value = "驾驶员信息展示")
    @RequestMapping(value = "/driverMessageShow",method = RequestMethod.GET)
    public LayuiTablePagingResult getDriverMessageShow(Integer page,Integer size,String vehicleNumber){
        LayuiTablePagingResult result=null;
        if (vehicleNumber!=null&&vehicleNumber.length()<3){
            result=new LayuiTablePagingResult();
            result.setCode("1009");
            result.setMsg("请输入车牌号不少于3位");
            return result;
        }
        PageHelper.startPage(page,size);
        if (vehicleNumber!=null){
            vehicleNumber=vehicleNumber.toUpperCase();
        }
        List<Map<String,Object>>driverList=disStaffMapper.selectDriver(vehicleNumber);
        PageInfo pageInfo=new PageInfo(driverList);
        result = new LayuiTablePagingResult();
        result.setCode(RetCode.SUCCESS.getCode());
        result.setMsg(RetCode.SUCCESS.getMsg());
        result.setCount(pageInfo.getTotal());
        result.setData(pageInfo.getList());
        Long totalPages = pageInfo.getTotal() / size;
        if (pageInfo.getTotal() % size != 0){
            totalPages ++;
        }
        result.setTotalPages(totalPages);
        return result;
    }


    @ApiOperation(value = "请求上报电子运单接口")
    @MyLog(value = "请求上报电子运单")  //这里添加了AOP的自定义注解
    @RequestMapping(value = "/eBill",method = RequestMethod.POST)
    public JSONObject geteBill(String vehicleId,String param,HttpServletRequest request){
        Boolean flag=listerUtil.getRoleType(request);
        if (flag==false){
            String list = "{\"code\":1009,\"msg\":\"此账号为监管员账号,不可进行操作\"}";
            return JSONObject.parseObject(list);
        }
        Map map = new HashMap();
        map.put("vehicleId", vehicleId);//必传 车辆id
        map.put("param", param);
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if (map.get(str) == null || map.get(str) == "null" || map.get(str) == "") {
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String, String> headMap = new HashMap<>();
        headMap.put("clientCode", clientCode);
        String url = "http://" + Ip + ":" + port + "/dis/v1/platform/eBill";
        String result = HttpClientUtils.doPost(url, headMap, map);
        JSONObject json= JSONObject.parseObject(result);
        return json;
    }


 /*   @ApiOperation(value = "车辆所属平台")
    @RequestMapping(value = "/vehicleForPlatformMessage",method = RequestMethod.GET)
    public Response getVehicleForPlatformMessage(Integer ){

    }*/

}





























































































